﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using ManYor.Phone.Common;
using System.Windows.Controls.Primitives;

namespace ManYor
{
    public partial class SliderShow : PhoneApplicationPage
    {
        #region -- Private Field --
        private const int IMAGE_WIDTH = 480;
        /// <summary>
        /// 当前图片对象
        /// </summary>
        private Image ImgZoom = new Image();
        /// <summary>
        /// 缓存的图片数据源数组
        /// </summary>
        private List<Image> cachedImage;
        /// <summary>
        /// 弹出提示框
        /// </summary>
        private Popup pop;
        /// <summary>
        /// 但前页
        /// </summary>
        private TextBlock pageTb;
        /// <summary>
        /// ScrollView对象实例
        /// </summary>
        private ScrollViewer svInstance;
        /// <summary>
        /// Horizontal滚动条实例
        /// </summary>
        private ScrollBar horzionScrollBar;
        /// <summary>
        /// 图片数据源数组
        /// </summary>
        private IList<CommicFrame> frames;
        //默认图片Index
        private int currentIndex = 0;
        /// <summary>
        /// 上次滑动水平的偏移量
        /// </summary>
        private double lastOffsetX;
        /// <summary>
        /// 方向是否是从右向左滑动
        /// </summary>
        private bool isRightToLeft;
        /// <summary>
        /// 计时器
        /// </summary>
        private System.Threading.Timer timer;
        /// <summary>
        /// 指示是否可以接受触摸事件
        /// </summary>
        private bool onTouchEnableFlag=true;
        /// <summary>
        /// 上次的索引位置
        /// </summary>
        private int lastIndex;
        #endregion
        /// <summary>
        /// 构造器
        /// </summary>
        public SliderShow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SliderShow_Loaded);
            InitializePopupPageNumber();
            timer = new System.Threading.Timer(TimerCallback);             
        }

        /// <summary>
        /// 计时器自动复位,在onTouchEnableFlag为false的时间内，禁止触发导航事件
        /// </summary>
        /// <param name="state"></param>
        private void TimerCallback(object state)
        {           
            onTouchEnableFlag = true;
            this.Dispatcher.BeginInvoke(new Action(() => { 
                ScrollingEnable = true;
                svInstance.ScrollToHorizontalOffset(lastIndex);  
            }));            
        }
        /// <summary>
        /// 初始化页码
        /// </summary>
        private void InitializePopupPageNumber()
        {
            pop = new Popup();
            pop.HorizontalOffset = 0;
            pop.VerticalOffset = 745;

            StackPanel panel1 = new StackPanel();
            panel1.Background = new SolidColorBrush(Colors.Transparent);
            pageTb = new TextBlock();
            pageTb.Text = "10/21";
            pageTb.Foreground = new SolidColorBrush(Colors.White);
            pageTb.FontSize = 25;
            pageTb.Margin = new Thickness(5.0);
            panel1.Children.Add(pageTb);
            pop.Child = panel1;
            pop.IsOpen = true;
        }

        /// <summary>
        /// 获取或设置当前页码文本
        /// </summary>
        private string PageNumber
        {
            get { return pageTb.Text; }
            set { pageTb.Text = value; }
        }
        /// <summary>
        /// 是否禁用滚动
        /// </summary>
        private bool ScrollingEnable
        {
            set
            {
                if (value)
                {
                    ScrollViewer.SetHorizontalScrollBarVisibility(svInstance, ScrollBarVisibility.Hidden);
                }
                else
                {
                    ScrollViewer.SetHorizontalScrollBarVisibility(svInstance, ScrollBarVisibility.Disabled);
                }
            }
        }
        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SliderShow_Loaded(object sender, RoutedEventArgs e)          
        {
            //string[] arr = new string[] { "Images/sample.jpg", "Images/sample2.jpg", "Images/sample3.jpg", "Images/sample4.jpg",
            //                                "Images/sample5.jpg","Images/sample6.jpg"};

            frames = new List<CommicFrame>() { new CommicFrame() { Source = "Images/01.jpg" },
                                                new CommicFrame() { Source = "Images/02.jpg" },
                                                new CommicFrame() { Source = "Images/03.jpg" },
                                                new CommicFrame() { Source = "Images/04.jpg" },
                                                new CommicFrame() { Source = "Images/05.jpg" },
                                                new CommicFrame() { Source = "Images/06.jpg" },
                                                new CommicFrame() { Source = "Images/07.jpg" }};


            ImageList.DataContext = frames;
            ImageList.Loaded += new RoutedEventHandler(ImageList_Loaded);
            
        }

        /// <summary>
        /// 列表载入完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageList_Loaded(object sender, RoutedEventArgs e)
        {
            InitilationImageEvent();
            //加载ScrollBar事件
            var svs = Common.FindAllChildOfType<ScrollViewer>(ImageList);
            if (svs != null && svs.Count() > 0)
            {
                svInstance = svs[0];
            }
            //sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
            //ScrollViewer.SetHorizontalScrollBarVisibility(sv, ScrollBarVisibility.Visible);
            FrameworkElement fe = VisualTreeHelper.GetChild(svInstance, 0) as FrameworkElement;
            if (fe != null)
            {
                VisualStateGroup vsg = Common.FindVisualState(fe, "ScrollStates");
                vsg.CurrentStateChanging += new EventHandler<VisualStateChangedEventArgs>(vsg_CurrentStateChanging);
                vsg.CurrentStateChanged += new EventHandler<VisualStateChangedEventArgs>(vsg_CurrentStateChanged);
            }

            var bars = Common.FindAllChildOfType<ScrollBar>(ImageList);
            if (bars != null && bars.Count() > 0)
            {
                foreach (var bar in bars)
                {
                    if (bar.Orientation == System.Windows.Controls.Orientation.Horizontal)
                    {
                        horzionScrollBar = bar;
                        bar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(ScrollBar_ValueChanged);                       
                       
                        //bar.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(bar_ManipulationCompleted);

                    }
                }
            }
        }

        /// <summary>
        /// 滚动事件已经发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void vsg_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            if (!onTouchEnableFlag)
                return;
            //var o = sender;
            //ScrollViewer.SetHorizontalScrollBarVisibility(svInstance, ScrollBarVisibility.Disabled);
            Debug.WriteLine("vsg_CurrentStateChanged:");
            ///向右滑动
            if (isRightToLeft)
            {
                //大于一半，往后翻页
                if (((int)lastOffsetX*10 + 0.5) > lastOffsetX*10){ JumpToImageFrame(false);  } 
                else {JumpToImageFrame(true);}
            }
            //往左滑动
            else
            {
                //小于一半，往后翻页
                if (((int)lastOffsetX * 10 - 0.5) > lastOffsetX * 10){ JumpToImageFrame(true);}                
                else{JumpToImageFrame(false);}
            }
        }

        void vsg_CurrentStateChanging(object sender, VisualStateChangedEventArgs e)
        {            
            var o=svInstance.GetValue(ScrollViewer.HorizontalOffsetProperty);
            Debug.WriteLine("vsg_CurrentStateChanging:" + horzionScrollBar.Value);
          
        }      
        /// <summary>
        /// 初始化图片缩放事件
        /// </summary>
        private void InitilationImageEvent()
        {
            cachedImage = Common.FindAllChildOfType<Image>(ImageList);
            foreach (Image img in cachedImage)
            {
                var gs = GestureService.GetGestureListener(img);
                gs.PinchStarted += new EventHandler<PinchStartedGestureEventArgs>(OnPinchStarted);
                gs.PinchDelta += new EventHandler<PinchGestureEventArgs>(OnPinchDelta);
                gs.DragDelta += new EventHandler<DragDeltaGestureEventArgs>(OnDragDelta);
                // gs.Tap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnTap);
                gs.DoubleTap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnDoubleTap);
                gs.Flick += new EventHandler<FlickGestureEventArgs>(OnFlick);               
                if((Guid)img.Tag==frames[currentIndex].ID)
                {
                    ImgZoom = img; 
                }
            }
            
        }
       
 

        #region Flick Event handlers

        /// <summary>
        /// 手指扫动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFlick(object sender, FlickGestureEventArgs e)
        {
            return;
           
            if (TotalImageScale > 1.05F)
            {
                ScrollingEnable = false;
                return;
            }
            else
            {
                ScrollingEnable = true;
            }
            JumpToImageFrame(e.VerticalVelocity>0);
            Debug.WriteLine("OnFlick");
        }

        #endregion     

        /// <summary>
        /// 跳转到指定页的图片
        /// </summary>
        /// <param name="flag"></param>
        private void JumpToImageFrame(bool flag)
        {
            if (flag)
            {
                if (currentIndex + 1 > frames.Count() )
                    currentIndex = frames.Count() - 1;
                this.lastIndex = currentIndex + 1;
                svInstance.ScrollToHorizontalOffset(currentIndex + 1);               
                currentIndex++;
            }
            else
            {
                if (currentIndex<1)
                    currentIndex = 1;
               this.lastIndex = currentIndex - 1;
               svInstance.ScrollToHorizontalOffset(currentIndex - 1);               
               currentIndex--;
            }
            //移除多点缩放事件
            foreach (var img in cachedImage)
            {
                var gs = GestureService.GetGestureListener(img);
                gs.PinchStarted -= new EventHandler<PinchStartedGestureEventArgs>(OnPinchStarted);
                gs.PinchDelta -= new EventHandler<PinchGestureEventArgs>(OnPinchDelta);
                gs.DragDelta -= new EventHandler<DragDeltaGestureEventArgs>(OnDragDelta);
                // gs.Tap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnTap);
                gs.DoubleTap -= new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnDoubleTap);
                gs.Flick -= new EventHandler<FlickGestureEventArgs>(OnFlick);               
            }
            InitilationImageEvent();
            PageNumber = currentIndex.ToString()+"/"+frames.Count();
            onTouchEnableFlag = false;
            this.ScrollingEnable = false;
            this.timer.Change(500, 0);
           
        }
        /// <summary>
        /// 滚动条已经滚动完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScrollBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!onTouchEnableFlag)
                return;
            Debug.WriteLine(string.Format("ScrollBar_ValueChanged {0}", e.NewValue));           
            if ((e.NewValue - currentIndex) >= 1)
            {
                JumpToImageFrame(true);
            }
            else if ((currentIndex - e.NewValue) >= 1)
            {
                JumpToImageFrame(false);
            }
            this.horzionScrollBar.IsEnabled = false;
            lastOffsetX = e.NewValue;
            isRightToLeft = e.NewValue > e.OldValue;            
            Debug.WriteLine(string.Format("ScrollBar_ValueChanged {0}", e.NewValue ));           
        }      
    }
}